
#include "protocol.h"
#include "receive_frame.h"

#define PHASE_NUMBER 4

/* node number per phase */
#define NODE_NUMBER 3

#define BLOCK 1
#define FREE 0

typedef struct
{
	unsigned int node_id;
	unsigned int car_status;
	unsigned char message_id;	/* The previous frame message_id */
}Node;

typedef struct
{
	Node node_info[NODE_NUMBER];
}Phase;

int protocol_C4(unsigned char *frame_data)
{
	static Phase c4_info[PHASE_NUMBER] = {0};
	int phase = frame_data[14];
	int loop_i = 0;
	unsigned char command_buf[] = {0x5A, 0x5A, 0x06, 0xAA, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00};
	int id = frame_data[0] << 8 | frame_data[11] << 4 | frame_data[12];


	for (loop_i = 0; loop_i < NODE_NUMBER; loop_i++)
	{
		if (c4_info[phase].node_info[loop_i].node_id == 0 && c4_info[phase].node_info[loop_i].node_id == id)
		{
			if (c4_info[phase].node_info[loop_i].message_id == frame_data[18])
			{
				return 0;
			}
			c4_info[phase].node_info[loop_i].car_status = frame_data[13];
			c4_info[phase].node_info[loop_i].message_id = frame_data[18];
			if (c4_info[phase].node_info[loop_i].car_status == 0)
			{
				c4_info[phase].node_info[loop_i].node_id = 0;
				return 0;
			}
			c4_info[phase].node_info[loop_i].node_id = id;
			break;
		}
	}


	for (loop_i = 0; loop_i < NODE_NUMBER; loop_i++)
	{
		if (c4_info[phase].node_info[loop_i].car_status == FREE)
		{
			return 0;
		}
	}

	command_buf[5] = phase;
	write(sockfd, command_buf, sizeof(command_buf));
	return 0;
}


